package me.ylduan.framework.util;

/**
 * @author Zero
 * @created 2017/5/9 17:01
 */
public final class CastUtil {
    private CastUtil() {}

    public static String castString(Object obj) {
        return CastUtil.castString(obj, "");
    }

    public static String castString(Object obj, String defaultValue) {
        return obj != null ? String.valueOf(obj) : defaultValue;
    }

    public static double castDouble(Object obj) {
        return castDouble(obj, 0.0);
    }

    public static double castDouble(Object obj, double defaultValue) {
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    defaultValue = Double.parseDouble(strValue);
                } catch (NumberFormatException ignored) {
                }
            }
        }
        return defaultValue;
    }

    public static long castLong(Object obj) {
        return castLong(obj, 0L);
    }

    public static long castLong(Object obj, long defaultValue) {
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    defaultValue = Long.parseLong(strValue);
                } catch (NumberFormatException ignored) {
                }
            }
        }
        return defaultValue;
    }

    public static int castInt(Object obj) {
        return castInt(obj, 0);
    }

    public static int castInt(Object obj, int defaultValue) {
        if (obj != null) {
            String strValue = castString(obj);
            if (StringUtil.isNotEmpty(strValue)) {
                try {
                    defaultValue = Integer.parseInt(strValue);
                } catch (NumberFormatException ignored) {
                }
            }
        }
        return defaultValue;
    }

    public static boolean castBoolean(Object obj) {
        return castBoolean(obj, false);
    }

    public static boolean castBoolean(Object obj, boolean defaultValue) {
        if (obj != null) {
            return Boolean.parseBoolean(castString(obj));
        }
        return defaultValue;
    }
}